package com.lxy.cxcyxmmsbackend.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxy.cxcyxmmsbackend.sys.entity.CxcyXm;
import com.lxy.cxcyxmmsbackend.sys.entity.QxglUser;
import com.lxy.cxcyxmmsbackend.sys.entity.Xmkj;
import com.lxy.cxcyxmmsbackend.sys.entity.XmkjDsjl;
import com.lxy.cxcyxmmsbackend.sys.exceptionHandle.exce.NormalException;
import com.lxy.cxcyxmmsbackend.sys.req.PageReq;
import com.lxy.cxcyxmmsbackend.sys.res.Result;
import com.lxy.cxcyxmmsbackend.sys.service.CxcyXmService;
import com.lxy.cxcyxmmsbackend.sys.service.QxglUserService;
import com.lxy.cxcyxmmsbackend.sys.service.XmfjService;
import com.lxy.cxcyxmmsbackend.sys.service.XmkjSqService;
import com.lxy.cxcyxmmsbackend.sys.utils.UUIDUtil;
import com.lxy.cxcyxmmsbackend.sys.utils.UpPhotoNameUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 项目空间
 *
 * @author 刘新颖
 * @since 2024-01-07
 */
@Api(tags = "项目空间")
@RestController
@RequestMapping("/xmkj")
public class XmfjController {

    @Autowired
    XmfjService xmfjService;

    @Autowired
    CxcyXmService cxcyXmService;

    @Resource
    QxglUserService qxglUserService;

    @Autowired
    Environment environment;

    @ApiOperation("查询项目空间列表")
    @PostMapping("/queryXmkj")
    @Transactional
    public Result queryXmkj(@RequestBody PageReq pageReq) {
        Integer limitS = pageReq.getCurrentPage();
        Integer pageS = pageReq.getPageSize();
        Page<Xmkj> pages = new Page<>(limitS, pageS);
        QueryWrapper<Xmkj> wrapper = new QueryWrapper<>();

        String kjhm = pageReq.getKeyWord().get("kjhm");

        if (kjhm != null && !"".equals(kjhm)) {
            wrapper.lambda().eq(Xmkj::getXmfjHm, kjhm);
        }

        wrapper.orderByAsc("XMFJ_HM");
        IPage<Xmkj> page = xmfjService.page(pages, wrapper);
        List<Xmkj> records1 = page.getRecords();
        for (Xmkj xmkj : records1) {
            QueryWrapper<CxcyXm> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().like(CxcyXm::getXmKjhm, xmkj.getXmfjHm());
//            Date now = new Date();
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            String nowStr = format.format(now);
//            queryWrapper.le("XM_RZSJ",nowStr).ge("XM_TZSJ",nowStr);
            CxcyXm one = cxcyXmService.getOne(queryWrapper);
            if (one != null) {
                xmkj.setXmBh(one.getXmBh());
                xmkj.setXmMc(one.getXmMc());
                xmkj.setXmfjJrsj(one.getXmRzsj());
            }
        }


        HashMap<Object, Object> map = new HashMap<>();

        map.put("pageNo", limitS);
        map.put("pageSize", pageS);
        List<Xmkj> records = page.getRecords();

        map.put("rows", records);
        map.put("total", page.getTotal());
        map.put("pageNums", (int) Math.ceil((double) page.getTotal() / pageS));
        return Result.success("查询项目房间列表成功", map);
    }


    @ApiOperation("查询空闲项目空间列表")
    @PostMapping("/queryXmkjKx")
    public Result queryXmkj() {
        QueryWrapper<Xmkj> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Xmkj::getStatus,"0");

        List<Xmkj> list = xmfjService.list(wrapper);
        if (list == null || list.isEmpty()){
            throw new NormalException("无空闲房间!");
        }
        return Result.success("查询空闲房间成功",list);
    }

    @ApiOperation("查询项目空间详情")
    @GetMapping("/queryXmkjDetail/{xmfjBh}")
    @Transactional
    public Result queryXmkjDetail(@PathVariable("xmfjBh") String xmfjBh) {
        QueryWrapper<Xmkj> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Xmkj::getXmfjBh, xmfjBh);
        Xmkj one = xmfjService.getOne(queryWrapper);
        if (one == null) {
            throw new NormalException("获取项目空间信息失败！");
        }
        return Result.success("获取项目空间信息成功！", one);
    }


    @ApiOperation("保存项目空间信息")
    @PostMapping("/saveXmkj")
    @Transactional
    public Result saveXmkj(@RequestBody Xmkj xmkj, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        if ("".equals(xmkj.getXmfjBh()) || xmkj.getXmfjBh() == null) {
            xmkj.setXmfjBh(UUIDUtil.getUUID8("F", 6));
            xmkj.setStatus("0");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            xmkj.setXmfjQysj(format.format(new Date(System.currentTimeMillis())));
            xmkj.setXmfjQyrbh(userBh);
            xmkj.setXmfjQyrmc(user.getUserMc());
            boolean save = xmfjService.save(xmkj);
            if (!save) {
                throw new NormalException("新增项目撤销申请失败");
            }
        } else {
            boolean save = xmfjService.updateById(xmkj);
            if (!save) {
                throw new NormalException("修改项目撤销申请失败");
            }
        }

        return Result.success("保存项目撤销申请成功", xmkj);
    }


    @ApiOperation("停用项目空间信息")
    @PostMapping("/stopXmkj")
    @Transactional
    public Result stopXmkj(@RequestBody Xmkj xmkj, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        xmkj.setStatus("-1");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        xmkj.setXmfjTysj(format.format(new Date(System.currentTimeMillis())));
        xmkj.setXmfjTyrbh(userBh);
        xmkj.setXmfjTyrmc(user.getUserMc());
        boolean save = xmfjService.updateById(xmkj);
        if (!save) {
            throw new NormalException("停用项目空间信息失败");
        }
        return Result.success("停用项目空间信息成功", xmkj);
    }

    @ApiOperation("启用项目空间信息")
    @PostMapping("/startXmkj/{xmfjBh}")
    @Transactional
    public Result startXmkj(@PathVariable("xmfjBh") String xmfjBh) {
        Xmkj xmkj = xmfjService.getById(xmfjBh);
        xmkj.setStatus("0");
        boolean remove = xmfjService.updateById(xmkj);
        if (!remove) {
            throw new NormalException("启用项目空间信息失败");
        }
        return Result.success("启用项目空间信息成功", xmkj);
    }

    @ApiOperation("删除项目空间信息")
    @PostMapping("/removeXmkj/{bh}")
    @Transactional
    public Result removeXmkj(@PathVariable("bh") String bh) {
        boolean remove = xmfjService.removeById(bh);
        if (!remove) {
            throw new NormalException("修改项目撤销申请失败");
        }
        return Result.success("修改项目撤销申请成功", null);
    }

    @ApiOperation("上传项目空间实景图")
    @RequestMapping("uploadSjt")
    public String uploadTX(@RequestParam("file") MultipartFile file, HttpServletRequest request, String xmfjBh) {
        QueryWrapper<Xmkj> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Xmkj::getXmfjBh, xmfjBh);
        Xmkj xmkj = xmfjService.getOne(wrapper);

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
            String url = environment.getProperty("front-assert-url.xmfjsjt");
            Path path = Paths.get(url + fileName);
            Files.write(path, bytes);//写入文件
            String avatar_url = fileName;
            xmkj.setXmfjSjt(avatar_url);
            boolean b = xmfjService.updateById(xmkj);

            System.out.println(fileName + "\n");
            return fileName;//返回文件名字
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}

